package ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class TestReentrantLock5 {
    static final Object room = new Object();
    static ReentrantLock ROOOM = new ReentrantLock();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;
    //等待烟的休息室
    static Condition waitCigaretteSet = ROOOM.newCondition();
    //等待外卖的休息室
    static Condition waitTakeout = ROOOM.newCondition();

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            ROOOM.lock();
            try{
                log.debug("有烟没？[{}]",hasCigarette);
                while(!hasCigarette){
                    log.debug("没烟，先歇会！");
                    try{
                       waitCigaretteSet.await();
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
                log.debug("有烟没？[{}]",hasCigarette);
                if(hasCigarette){
                    log.debug("可以开始干活了");
                }else{
                    log.debug("没干成活。。。");
                }
            }finally {
                ROOOM.unlock();
            }
        },"小南").start();


        new Thread(() -> {
            ROOOM.lock();
            try{
                log.debug("有外卖没？[{}]",hasTakeout);
                while(!hasTakeout){
                    log.debug("没外卖，先歇会！");
                    try{
                        waitTakeout.await();
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
                log.debug("有外卖没？[{}]",hasTakeout);
                if(hasTakeout){
                    log.debug("可以开始干活了");
                }else{
                    log.debug("没干成活。。。");
                }
            }finally {
                ROOOM.unlock();
            }
        },"小女").start();

        Thread.sleep(1000);
        new Thread(() -> {
            ROOOM.lock();
            try{
                hasTakeout = true;
                waitTakeout.signal();
            }finally {
                ROOOM.unlock();
            }
        },"送外卖的").start();

        Thread.sleep(1000);
        new Thread(() -> {
            ROOOM.lock();
            try{
                hasCigarette = true;
                waitCigaretteSet.signal();
            }finally {
                ROOOM.unlock();
            }
        },"送烟的").start();

    }
}
